using ColorFillGame.Domain.Entities;
using ColorFillGame.Domain.ValueObjects;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;

namespace ColorFillGame.Infrastructure.Data;

public class AppDbContext : DbContext
{
    public DbSet<Game> Games { get; set; }
    public DbSet<Player> Players { get; set; }

    public AppDbContext(DbContextOptions<AppDbContext> options)
        : base(options)
    {}

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        // 配置Game实体
        modelBuilder.Entity<Game>()
            .HasKey(g => g.Id);

        // 配置GameGrid作为JSON存储
        modelBuilder.Entity<Game>()
            .Property(g => g.Grid)
            .HasConversion(
                grid => JsonConvert.SerializeObject(grid),
                json => JsonConvert.DeserializeObject<GameGrid>(json)
            )
            .HasColumnType("jsonb") // PostgreSQL的JSONB类型
            .IsRequired();

        // 配置Game和Player的一对多关系
        modelBuilder.Entity<Game>()
            .HasMany(g => g.Players)
            .WithOne()
            .HasForeignKey(p => p.GameId);

        // 配置Player实体
        modelBuilder.Entity<Player>()
            .HasKey(p => p.Id);

        // 配置PlayerColor作为Owned实体类型
        modelBuilder.Entity<Player>()
            .OwnsOne(p => p.Color, c =>
            {
                c.Property(color => color.Name).HasMaxLength(20);
                c.Property(color => color.HexCode).HasMaxLength(7);
            });
    }
}